# Read username, output from non-empty factory, drop connections.
# Use deferreds, to minimize synchronicity assumptions.

from twisted.internet import protocol,reactor,defer,utils
from twisted.protocols import basic

class FingerProtocol(basic.LineReceiver):
    def lineReceived(self, user):
        d = self.factory.getUser(user)
        
        def onError(err):
            return "Internal error in server"

        d.addErrback(onError)
        
        def writeResponse(message):
            self.transport.write(message + '\r\n')
            self.transport.loseConnection()

        d.addCallback(writeResponse)
        
        #self.transport.write(self.factory.getUser(user) + "\r\n")
        #self.transport.loseConnection()

class FingerFactory(protocol.ServerFactory):
    protocol = FingerProtocol
    
    def __init__(self, **kwrgs):
        self.users = kwrgs
        print type(self.users)
    
    def getUser(self, user):
        return utils.getProcessOutput("finger",[user])
        #return defer.succeed(self.users.get(user, 'No such user'))

reactor.listenTCP(1084, FingerFactory(moshez='Happy and well'))
reactor.run()